package com.horse.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.inapp.util.BillingService;
//import com.openfeint.api.resource.Achievement;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.StatFs;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class Utils {

	public static void showAlertMessage(Context context, int icon,
			String title, String message) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setIcon(icon);
		builder.setMessage(message).setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(final DialogInterface dialog,
							final int id) {

					}
				});
		final AlertDialog alert = builder.create();
		alert.setTitle(title);
		alert.show();
	}

	public static long getSDCardFreeSpace() {
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());
		long bytesAvailable = (long) stat.getBlockSize()
				* (long) stat.getBlockCount();
		long megAvailable = bytesAvailable / 1048576;
		return megAvailable;
	}

	public static void vibratePhone(Context context) {
		Vibrator v = (Vibrator) context
				.getSystemService(Context.VIBRATOR_SERVICE);
		v.vibrate(300);

	}

	public static boolean isMounted() {
		boolean mounted = Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState());
		return mounted;
	}

	public static void showAlertMessage(Context context, String title,
			String message) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message).setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(final DialogInterface dialog,
							final int id) {

					}
				});
		final AlertDialog alert = builder.create();
		alert.setTitle(title);
		alert.show();
	}

	private static MediaPlayer mp = null;

	/** Stop old song and start new one */
	public static void play(Context context, int resource) {
		stop(context);
		mp = MediaPlayer.create(context, resource);
		mp.setLooping(false);
		mp.start();
	}

	/** Stop the music */
	public static void stop(Context context) {
		if (mp != null) {
			mp.stop();
			mp.release();
			mp = null;
		}
	}

	public static String getFileName(String fileName) {
		String targetFileName = fileName.toLowerCase();
		if (targetFileName.contains(" ")) {
			targetFileName = targetFileName.replace(" ", "_");
		}
		if (targetFileName.charAt(0) == '1') {
			targetFileName = targetFileName.replace("1", "_1");
		}
		if (targetFileName.charAt(0) == '2') {
			targetFileName = targetFileName.replace("2", "_2");
		}
		if (targetFileName.charAt(0) == '3') {
			targetFileName = targetFileName.replace("3", "_3");
		}

		return targetFileName;
	}

	public static synchronized void playFile(File file, Context context,
			OnCompletionListener ocl) {
		try {
			stopPlaying();
			MediaPlayer mPlayer = new MediaPlayer();
			if (ocl != null) {
				mPlayer.setOnCompletionListener(ocl);
			}
			mPlayer.setDataSource(file.getAbsolutePath());
			mPlayer.prepare();
			mPlayer.start();
			mediaPlayerRec = mPlayer;
		} catch (Exception e) {
			if (ocl != null) {
				ocl.onCompletion(null);
			}
			e.printStackTrace();
		}
	}

	private static MediaPlayer mediaPlayerRec = null;

	public static synchronized void stopPlaying() {
		try {
			if (mediaPlayerRec != null) {
				try {
					mediaPlayerRec.stop();
				} catch (Exception e) {
					e.printStackTrace();
				}
				mediaPlayerRec.release();
				mediaPlayerRec = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static byte[] getFileData(Context context, String fileName) {
		byte[] ret = null;
		try {
			InputStream is = context.getAssets().open(fileName);
			byte[] data = new byte[2048];
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int read;
			while ((read = is.read(data)) != -1) {
				baos.write(data, 0, read);
			}
			is.close();
			ret = baos.toByteArray();
			baos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
		int width = bm.getWidth();
		int height = bm.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
				matrix, false);

		return resizedBitmap;

	}

	// public static final boolean putLevelUnlocked(Context context, String key,
	// boolean value) {
	// return PreferenceManager.getDefaultSharedPreferences(context).edit()
	// .putBoolean(key, value).commit();
	// }
	//
	// public static final boolean getLevelUnlocked(Context context, String key)
	// {
	// return PreferenceManager.getDefaultSharedPreferences(context)
	// .getBoolean(key, false);
	// }

	public static final boolean putLevelHighestScore(Context context,
			String key, int score) {
		return PreferenceManager.getDefaultSharedPreferences(context).edit()
				.putInt(key, score).commit();
	}

	public static final int getLevelHighestScore(Context context, String key) {
		return PreferenceManager.getDefaultSharedPreferences(context).getInt(
				key, 0);
	}

	public static final boolean putPrecentage(Context context, String key,
			int score) {
		return PreferenceManager.getDefaultSharedPreferences(context).edit()
				.putInt(key, score).commit();
	}

	public static final int getPercentage(Context context, String key) {
		return PreferenceManager.getDefaultSharedPreferences(context).getInt(
				key, 0);
	}

	public static boolean isDeviceOnline(Context context) {
		boolean ret = true;
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo i = cm.getActiveNetworkInfo();
		if (i == null || (!i.isConnected()) || (!i.isAvailable())) {
			ret = false;
		}
		return ret;
	}

	public static final ProgressDialog getProgressDialog(Context context,
			String title, String message) {
		ProgressDialog progressDialog = new ProgressDialog(context);
		progressDialog.setTitle(title);
		progressDialog.setMessage(message);
		progressDialog.setMax(13);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setCancelable(true);
		progressDialog.setIndeterminate(true);
		return progressDialog;
	}

	public static String getAndroidFormattedUrl(String url) {
		if (url != null) {
			url = url.replace(" ", "%20");
		}
		return url;
	}

	public static final File ROOT = Environment.getExternalStorageDirectory();

	public static final File getFile(int level, String fileName, Context context) {
		File ret = null;
		try {
			File file = new File(ROOT, "horse360/level " + level + "/");
			if (!file.exists()) {
				file.mkdirs();
			}
			ret = new File(file, fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static File[] getFileList(int level) {
		File file = new File(ROOT, "horse360/level " + level);
		return file.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File file, String name) {
				if (name.endsWith(".png")) {
					return true;
				}
				return false;
			}
		});
	}

//	public static String[] getFileList(String dirName, final List<String> names) {
//		File file = new File(ROOT, "horse360/" + dirName);
//		if(!file.exists()){
//			file.mkdirs();
//		}
//		String[] ret = file.list(new FilenameFilter() {
//
//			@Override
//			public boolean accept(File file, String name) {
//				return names.contains(name);
//			}
//		});
//		if(ret==null){
//			ret = new String[0];
//		}
//		Log.i("DREG", "FILE_SIZE="+ret.length+",INPUT_SIZE="+names.size());
//		return ret;
//	}

	public static boolean containsAllFiles(String dirName, final List<String> names) {
		File file = new File(ROOT, "horse360/" + dirName);
		if(!file.exists()){
			file.mkdirs();
		}
		String[] ret = file.list(new FilenameFilter() {

			@Override
			public boolean accept(File file, String name) {
				return names.contains(name);
			}
		});
		if(ret==null){
			return false;
		}else{
			Log.i("DREG", "FILE_SIZE="+ret.length+",INPUT_SIZE="+names.size());
			return (ret.length>=names.size());
		}
	}
	
	public static void downloadFile(int level, String fileName, String url,
			Context context) throws Exception {
		File file = getFile(level, fileName, context);
		if (!file.exists()) {
			try {
				URL u = new URL(url);
				HttpURLConnection c = (HttpURLConnection) u.openConnection();
				c.setConnectTimeout(5000);
				c.setRequestMethod("GET");
				c.connect();
				if (c.getResponseCode() == HttpURLConnection.HTTP_OK) {
					InputStream in = c.getInputStream();
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int len1 = 0;
					while ((len1 = in.read(buffer)) != -1) {
						if (len1 > 0) {
							baos.write(buffer, 0, len1);
						}
					}
					buffer = baos.toByteArray();
					baos.close();
					try {
						if (buffer != null && buffer.length > 0) {
							FileOutputStream f = new FileOutputStream(file);
							f.write(buffer);
							f.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

					in.close();
					c.disconnect();
				} else {
					c.disconnect();

				}
			} catch (Exception e) {
				e.printStackTrace();

			}
		}
	}

	public static File getFile(Context context, int resId) throws Exception {
		File file = new File(Environment.getExternalStorageDirectory()
				.toString());
		if (!file.exists()) {
			try {

				InputStream in = context.getResources().openRawResource(resId);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len1 = 0;
				while ((len1 = in.read(buffer)) != -1) {
					if (len1 > 0) {
						baos.write(buffer, 0, len1);
					}
				}
				buffer = baos.toByteArray();
				baos.close();
				try {
					if (buffer != null && buffer.length > 0) {
						FileOutputStream f = new FileOutputStream(file);
						f.write(buffer);
						f.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}

			} catch (Exception e) {

				e.printStackTrace();
				return null;

			}
		}
		return file;
	}

	public static String[] getUniqueArray(String[] inputParent) {
		Set<String> tempArray = new HashSet<String>(Arrays.asList(inputParent));
		String[] uniqueArray = tempArray.toArray(new String[tempArray.size()]);
		return uniqueArray;
	}

	public static float getWidthDpiFactor(Activity activity) {
		int orientation = activity.getResources().getConfiguration().orientation;
		float widthFactor = 0;
		int width = 0;
		if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
			width = activity.getWindowManager().getDefaultDisplay().getWidth();
		} else {
			width = activity.getWindowManager().getDefaultDisplay().getHeight();
		}

		widthFactor = ((float) width) / 480;
		return widthFactor;
	}

	public static final ProgressDialog getDialog(Context context, String message) {
		ProgressDialog progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage(message);
		progressDialog.setCancelable(true);
		progressDialog.setIndeterminate(true);
		return progressDialog;
	}

	public static float getHeightDpiFactor(Activity activity) {
		int orientation = activity.getResources().getConfiguration().orientation;
		float heightFactor = 0;
		int height = 0;
		if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
			height = activity.getWindowManager().getDefaultDisplay()
					.getHeight();
		} else {
			height = activity.getWindowManager().getDefaultDisplay().getWidth();
		}

		heightFactor = ((float) height) / 320;
		return heightFactor;
	}

	// private static boolean mainBundleDownloaded;
	// private static boolean isLevelUnlocked[] = new boolean[20];
	// private static boolean musclesDownloaded;
	// private static boolean hoovesDownloaded;
	// private static boolean tendonsDownloaded;
	// private static boolean headDownloaded;
	// private static boolean organsDownloaded;

	public static boolean[] getUnlockedLevels(
			SharedPreferences sharedPreferences) {

		boolean mainBundleDownloaded = BillingService.isPurchased(
				sharedPreferences, Constants.BUNDLE_ITEM_ID);
		boolean musclesDownloaded = BillingService.isPurchased(
				sharedPreferences, Constants.MUSCLE_ITEM_ID);
		boolean hoovesDownloaded = BillingService.isPurchased(
				sharedPreferences, Constants.HOOF_ITEM_ID);
		boolean tendonsDownloaded = BillingService.isPurchased(
				sharedPreferences, Constants.DEEP_ITEM_ID);
		boolean headDownloaded = BillingService.isPurchased(sharedPreferences,
				Constants.HEAD_ITEM_ID);
		boolean organsDownloaded = BillingService.isPurchased(
				sharedPreferences, Constants.ORGAN_ITEM_ID);
		boolean isLevelUnlocked[] = new boolean[20];
		isLevelUnlocked[0] = true;
		isLevelUnlocked[1] = true;
		isLevelUnlocked[2] = true;
		if (mainBundleDownloaded) {
			for (int i = 0; i < 20; i++) {
				isLevelUnlocked[i] = true;
			}
		} else {
			if (musclesDownloaded) {
				isLevelUnlocked[3] = true;
				isLevelUnlocked[4] = true;
			}
			if (hoovesDownloaded) {
				isLevelUnlocked[5] = true;
				isLevelUnlocked[6] = true;
				isLevelUnlocked[7] = true;
				isLevelUnlocked[8] = true;
			}
			if (tendonsDownloaded) {
				isLevelUnlocked[9] = true;
				isLevelUnlocked[10] = true;
				isLevelUnlocked[11] = true;
				isLevelUnlocked[12] = true;
			}
			if (headDownloaded) {
				isLevelUnlocked[13] = true;
				isLevelUnlocked[14] = true;
				isLevelUnlocked[15] = true;
			}
			if (organsDownloaded) {
				isLevelUnlocked[16] = true;
				isLevelUnlocked[17] = true;
				isLevelUnlocked[18] = true;
				isLevelUnlocked[19] = true;
			}
		}

		return isLevelUnlocked;
	}

	public static boolean[] getFilesDownloaded() {
		boolean isFilesDownloaded[] = new boolean[20];
		isFilesDownloaded[0] = true;
		isFilesDownloaded[1] = true;
		isFilesDownloaded[2] = true;
		
		if(Utils.containsAllFiles(Constants.MUSLES_DIRECTORY,Arrays.asList(ImageName.MUSCLES_IMAGES))){
			isFilesDownloaded[3] = true;
			isFilesDownloaded[4] = true;
			Log.i("DREG", "--------------CASE_1_TRUE");
		}else{
			Log.i("DREG", "--------------CASE_1_FALSE");
		}
		if(Utils.containsAllFiles(Constants.HOOFS_DIRECTORY,Arrays.asList(ImageName.HOOFS_IMAGES))){
			isFilesDownloaded[5] = true;
			isFilesDownloaded[6] = true;
			isFilesDownloaded[7] = true;
			isFilesDownloaded[8] = true;
			Log.i("DREG", "--------------CASE_2_TRUE");
		}else{
			Log.i("DREG", "--------------CASE_2_FALSE");
		}
		if(Utils.containsAllFiles(Constants.DEEP_MUSCLES_DIRECTORY,Arrays.asList(ImageName.TENDON_IMAGES))){
			isFilesDownloaded[9] = true;
			isFilesDownloaded[10] = true;
			isFilesDownloaded[11] = true;
			isFilesDownloaded[12] = true;
			Log.i("DREG", "--------------CASE_3_TRUE");
		}else{
			Log.i("DREG", "--------------CASE_3_FALSE");
		}
		if(Utils.containsAllFiles(Constants.HEAD_DIRECTORY,Arrays.asList(ImageName.HEAD_IMAGES))){
			isFilesDownloaded[13] = true;
			isFilesDownloaded[14] = true;
			isFilesDownloaded[15] = true;
			Log.i("DREG", "--------------CASE_4_TRUE");
		}else{
			Log.i("DREG", "--------------CASE_4_FALSE");
		}
		if(Utils.containsAllFiles(Constants.ORGANS_DIRECTORY,Arrays.asList(ImageName.ORGANS_IMAGES))){
			isFilesDownloaded[16] = true;
			isFilesDownloaded[17] = true;
			isFilesDownloaded[18] = true;
			isFilesDownloaded[19] = true;
			Log.i("DREG", "--------------CASE_5_TRUE");
		}else{
			Log.i("DREG", "--------------CASE_5_FALSE");
		}
		return isFilesDownloaded;
	}
	
	public static void downloadFiles(final Activity context,
			final List<DownloadingItem> downloadingItems,
			final DownloadCompletionListener dcl) {
		try {
			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;
				private int imageIndex = 0;
				private int totalFiles;
				private Exception exception;

				@Override
				protected void onPreExecute() {
					try {

						totalFiles = 0;
						for (int i = 0; i < downloadingItems.size(); i++) {
							totalFiles += downloadingItems.get(i)
									.getImageFileName().length;
						}
						progressDialog = new ProgressDialog(context);
						progressDialog.setMessage("Downloading....");
						progressDialog.setIndeterminate(false);
						progressDialog.setCancelable(false);
						progressDialog.setMax(totalFiles);
						progressDialog
								.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

						progressDialog.show();

					} catch (Exception e) {
						exception = e;
						e.printStackTrace();
					}
				}

				protected void onProgressUpdate(String... strings) {
					try {
						progressDialog.setProgress(imageIndex);
//						if (strings != null && strings.length > 0) {
//							new Achievement(strings[0])
//									.unlock(new Achievement.UnlockCB() {
//
//										@Override
//										public void onSuccess(boolean newUnlock) {
//											context.setResult(Activity.RESULT_OK);
//										}
//
//										@Override
//										public void onFailure(
//												String exceptionMessage) {
//											Toast.makeText(
//													context,
//													"Error ("
//															+ exceptionMessage
//															+ ") unlocking achievement.",
//													Toast.LENGTH_SHORT).show();
//											context.setResult(Activity.RESULT_CANCELED);
//										}
//
//									});
//						}
					} catch (Exception e) {
						exception = e;
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					try {
						DownloadingItem di;
						for (int i = 0; i < downloadingItems.size(); i++) {
							di = downloadingItems.get(i);
							for (int j = 0, k = di.getImageFileName().length; j < k; j++) {
								String url = di.getBASE_URL()
										+ "/"
										+ Utils.getAndroidFormattedUrl(di
												.getImageFileName()[j]);

								Downloader.downloadFile(
										di.getIMAGE_DIRECTORY(),
										di.getImageFileName()[j], url, context);
								imageIndex++;
								publishProgress();
							}
//							if (di.getACHIEVEMENT_ID() != null) {
//								publishProgress(di.getACHIEVEMENT_ID());
//							}
						}

					} catch (Exception e) {
						exception = e;
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(String unused) {
					progressDialog.dismiss();
					if (dcl != null) {
						if (exception == null) {
							dcl.onCompleteDownloading();
						} else {
							dcl.onDownloadError(exception);
						}
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
